package com.caopeng.javaee.service.ServiceImpl;

import com.caopeng.javaee.entity.student;
import com.caopeng.javaee.service.CourseStudentService;
import com.caopeng.javaee.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: javaee
 * @description: jdbc实验 课程学生实现
 * @author: caopeng
 * @create: 2018-12-10 11:45
 **/
@Service
public class CourseStudentServiceImpl implements CourseStudentService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private StudentService studentService;
    @Override
    public String  test(int course_id, int student_id) {
        //INSERT INTO course_student(course_id,student_id) VALUES(1,1);
        String sql="INSERT INTO course_student(course_id,student_id) VALUES("+course_id +","+student_id+")";
        jdbcTemplate.update(sql);
        return "yes";
    }

    @Override
    public String CourseAddStudent(int course_id, int student_id) {
        String sql="INSERT INTO course_student(course_id,student_id) VALUES("+course_id +","+student_id+")";
        jdbcTemplate.update(sql);
        return "CourseAddStudent执行";
    }

    @Override
    //写错了不应该写成string的应该返回一个list<student>的 妈蛋
    public List<String> Courseidfindstudent(int course_id) {
        String sql="SELECT student_id FROM course_student where course_id="+course_id;
        List<String> liststudentname=new ArrayList<String>();
        List<Map<String,Object>> list=jdbcTemplate.queryForList(sql);
        for(Map<String,Object> map:list){
            String student_name=studentService.SfindById(map.get("student_id").toString()).getName();
            System.out.println("打印出学生名字"+student_name);
            liststudentname.add(student_name);
        }
        return liststudentname;
    }

    @Override
    public List<student> Courseidfindstudentlist(int course_id) {
        String sql="SELECT student_id FROM course_student where course_id="+course_id;
        List <student> myList=new ArrayList<student>();
        List<Map<String,Object>> list=jdbcTemplate.queryForList(sql);
        for(Map<String,Object> map:list){
            student thestudent=studentService.SfindById(map.get("student_id").toString());
            System.out.println("打印出学生名字"+thestudent.getName());
            myList.add(thestudent);
        }
        return myList;
    }

    @Override
    public void insetStudent(List<student> studentList, String courseid) {
        for(int i=0;i<studentList.size();i++){
            String id=String.valueOf(studentList.get(i).getId());
            String sql="insert into course_student(course_id,student_id)VALUES("+courseid+","+id+")";
            jdbcTemplate.update(sql);
        }
    }
}

